
#include <time.h>
#include <boost/algorithm/string/replace.hpp>
#include <boost/regex.hpp>
#include <boost/lexical_cast.hpp>

#include "Builder.h"

using namespace std;

Builder::Builder(const configInfo::ConfigInfo& config)
{
  m_config = config;
}

Builder::~Builder(void)
{
}

void Builder::setDirValue(const string& key,string& dir)
{
  if(m_template.JieqiArticleConfigs[key].find(":") > 0)
  {
    dir = m_config.filepath ;
    dir += "/files/article/";
    dir += m_template.JieqiArticleConfigs[key];
//    XString::replaceAll(dir, "/", "\\");
  }
}

void Builder::setUrlValue(const string& key,string& url)
{
  if(m_template.JieqiArticleConfigs[key].length() > 0)
  {
    url = m_template.JieqiDefine["JIEQI_URL"] ;
    url += "/files/article/";
    url += m_template.JieqiArticleConfigs[key];
  }
}

void Builder::loadConfig()
{
  string strDefine ;
  m_file.readFile(m_config.filepath + "/configs/define.php", strDefine);
  std::string::const_iterator itr_begin = strDefine.begin();
  std::string::const_iterator itr_end = strDefine.end();
  boost::smatch matchs;
  boost::regex regexDefine("define\\('(.+?)','(.*)'\\);");
  while(boost::regex_search(itr_begin, itr_end, matchs, regexDefine, boost::regex_constants::match_not_dot_newline))
  {
    m_template.JieqiDefine[matchs[1]] = matchs[2];
    itr_begin = matchs[0].second;
  }

  string strSort;
  m_file.readFile(m_config.filepath + "/configs/article/sort.php", strSort);
  boost::regex regexSort("jieqiSort\\['article'\\]\\[(\\d*)\\] = array\\('layer' => '0', 'caption' => '(.+?)', 'shortname'");
  itr_begin = strSort.begin();
  itr_end = strSort.end();
  m_template.JieqiSort[0] = "未知分类";
  while(boost::regex_search(itr_begin, itr_end, matchs, regexSort, boost::regex_constants::match_not_dot_newline))
  {
    m_template.JieqiSort[boost::lexical_cast<int>(matchs[1])]=matchs[2];
    itr_begin = matchs[0].second;
  }

  string strConfigs;
  m_file.readFile(m_config.filepath + "/configs/article/configs.php", strConfigs);
  boost::regex regexConfigs("jieqiConfigs\\['article'\\]\\['(.+?)'\\] \\= '(.*)';");
  itr_begin = strConfigs.begin();
  itr_end = strConfigs.end();
  while(boost::regex_search(itr_begin, itr_end, matchs, regexConfigs, boost::regex_constants::match_not_dot_newline))
  {
    m_template.JieqiArticleConfigs[matchs[1]] = matchs[2];
    itr_begin = matchs[0].second;
  }
  if (m_template.JieqiArticleConfigs.find("indexcols") != m_template.JieqiArticleConfigs.end())
  {
    m_indexCols = boost::lexical_cast<int>(m_template.JieqiArticleConfigs["indexcols"]);
  }
  else
  {
    m_indexCols = 4;
  }

  setDirValue("htmldir", m_template.HtmlDir);
  setUrlValue("htmldir", m_template.HtmlUrl);

  setDirValue("txtdir", m_template.TxtDir);
  setUrlValue("txturl", m_template.TxtUrl);

  setDirValue("opfdir", m_template.OpfDir);
  setUrlValue("opfurl", m_template.OpfUrl);

  setDirValue("attachdir", m_template.AttachDir);
  setUrlValue("attachurl", m_template.AttachUrl);
}

void Builder::loadTheme()
{
  m_file.readFile(m_config.filepath + "/modules/article/templates/index.html", m_template.TempletsIndexHtml);
  m_file.readFile(m_config.filepath + "/modules/article/templates/style.html", m_template.TempletsContent);
  XString::replaceAll(m_template.TempletsIndexHtml, "?}{?else?}", "?}&nbsp;{?else?}");

  initializeReplaceTemplete(m_template.TempletsIndexHtml);
  initializeReplaceTemplete(m_template.TempletsContent);

  std::string::const_iterator itr_begin = m_template.TempletsIndexHtml.begin();
  std::string::const_iterator itr_end = m_template.TempletsIndexHtml.end();
  boost::smatch matchs;
  boost::regex regEx1("\\{\\?if\\s+\\$indexrows\\[i\\]\\.([^=]+?)\\s*==\\s*\"\"\\?\\}(.+?)\\{\\?else\\?\\}(.+?)\\{\\?/if\\?\\}");
  boost::regex regEx2("\\{\\?section name=i loop=\\$indexrows\\?\\}(.*)\\{\\?if \\$indexrows\\[i\\]\\.ctype == \"volume\"\\?\\}(.+?)\\{\\?else\\?\\}(.+?)\\{\\?/if\\?\\}(.*)\\{\\?/section\\?\\}");
  boost::regex regEx3("\\{\\?section name=i loop=\\$chapters\\?\\}(.+?)\\{\\?/section\?\\}");
  boost::regex regEx4("\\{\\?section name=i loop=\\$indexrows\\?\\}(.+?)\\{\\?if \\$indexrows\\[i\\]\\.ctype == \"volume\"\\?\\}(.+?)\\{\\?else\\?\\}(.+?)\\{\\?/if\\?\\}(.+?)\\{\\?/section\\?\\}");

  string strTemp;
  while(boost::regex_search(itr_begin, itr_end, matchs, regEx1, boost::regex_constants::match_single_line))
  {
    vector<string> strArr;
    strTemp.assign(matchs[2]);
    XString::replaceAll(strTemp, "&nbsp;", " ");
    strArr.push_back(strTemp);

    strTemp.assign(matchs[3]);
    XString::replaceAll(strTemp, "&nbsp;", " ");
    strArr.push_back(strTemp);

    m_template.Templets_indexchapterlist[matchs[1]] = strArr;
    itr_begin = matchs[0].second;
  }
  m_template.Templets_indexhtml = boost::regex_replace(m_template.TempletsIndexHtml, regEx1, "章节$1", boost::regex_constants::match_single_line);
  itr_begin = m_template.Templets_indexhtml.begin();
  itr_end = m_template.Templets_indexhtml.end();
  while(boost::regex_search(itr_begin, itr_end, matchs, regEx2, boost::regex_constants::match_single_line))
  {
    m_template.Templets_indextop = matchs[1];
    m_template.Templets_indexvolume = matchs[2];
    m_template.Templets_indexchapter = matchs[3];
    m_template.Templets_indexbottom = matchs[4];
    itr_begin = matchs[0].second;
  }
  m_template.Templets_indexhtml = boost::regex_replace(m_template.Templets_indexhtml, regEx2, "目录循环部分", boost::regex_constants::match_single_line);

}

bool Builder::createChapter(const configInfo::ConfigInfo& config, articleInfo::ArticleInfo& article, const chapterInfo::ChapterInfo& chapter)
{
  m_content.assign(m_template.TempletsContent);
  XString::replaceAll(m_content, "<{if $authorid > 0}><a href=\"<{$article_dynamic_url}>/userinfo.php?id=<{$authorid}>\" target=\"_blank\"><{$author}></a><{else}><{$author}><{/if}>", "<{$author}>");
  XString::replaceAll(m_content, "<{$author}>", article.author);
  XString::replaceAll(m_content, "<{$article_title}>", article.articlename);
  XString::replaceAll(m_content, "<{$jieqi_title}>", chapter.chaptername);
  XString::replaceAll(m_content, "<{$sortname}>", article.sortname);
  XString::replaceAll(m_content, "<{$jieqi_sitename}>", m_template.JieqiDefine["JIEQI_SITE_NAME"]);
  XString::replaceAll(m_content, "<{$jieqi_charset}>", m_config.charset);
  XString::replaceAll(m_content, "<{$meta_keywords}>", m_template.JieqiDefine["JIEQI_META_KEYWORDS"]);
  XString::replaceAll(m_content, "<{$meta_description}>", m_template.JieqiDefine["JIEQI_META_DESCRIPTION"]);
  XString::replaceAll(m_content, "<{$meta_author}>", "x1");
  XString::replaceAll(m_content, "<{$meta_copyright}>", m_template.JieqiDefine["JIEQI_META_COPYRIGHT"]);
  XString::replaceAll(m_content, "<{$new_url}>", m_template.JieqiDefine["JIEQI_URL"]);
  XString::replaceAll(m_content, "<{$indexrows[i].vname}>", chapter.volumeid);
  if(chapter.preview_page.length() >0)
  {
    XString::replaceAll(m_content, "{?$preview_page?}", chapter.preview_page + m_template.JieqiArticleConfigs["htmlfile"]);
    XString::replaceAll(m_content, "{?$preview_chapterid?}", chapter.preview_page);
    XString::replaceAll(m_content, "{?$preview_chapteridd?}", chapter.preview_page + "/");
  }
  else
  {
    XString::replaceAll(m_content, "{?$preview_page?}", "index" + m_template.JieqiArticleConfigs["htmlfile"]);
    XString::replaceAll(m_content, "{?$preview_chapterid?}", "");
    XString::replaceAll(m_content, "{?$preview_chapteridd?}", "");
  }
  if(chapter.next_page.length() >0)
  {
    XString::replaceAll(m_content, "{?$next_page?}", chapter.next_page + m_template.JieqiArticleConfigs["htmlfile"]);
    XString::replaceAll(m_content, "{?$next_chapterid?}", chapter.next_page);
    XString::replaceAll(m_content, "{?$next_chapteridd?}", chapter.next_page + "/");
  }
  else
  {
    XString::replaceAll(m_content, "{?$next_page?}", "index" + m_template.JieqiArticleConfigs["htmlfile"]);
    XString::replaceAll(m_content, "{?$next_chapterid?}", "");
    XString::replaceAll(m_content, "{?$next_chapteridd?}", "");
  }
  XString::replaceAll(m_content, "{?$index_page?}", "index" + m_template.JieqiArticleConfigs["htmlfile"]);
  XString::replaceAll(m_content, "{?$url_indexpage?}", "index" + m_template.JieqiArticleConfigs["htmlfile"]);
  XString::replaceAll(m_content, "{?$article_id?}", article.articleid);
  XString::replaceAll(m_content, "{?$chapter_id?}", chapter.chapterid);
  XString::replaceAll(m_content, "{?$dynamic_url?}", m_template.JieqiDefine["JIEQI_URL"]);
  XString::replaceAll(m_content, "{?$url_bookroom?}", m_template.JieqiDefine["JIEQI_URL"] + "/modules/article/");
  XString::replaceAll(m_content, "{?$url_articleinfo?}", m_template.JieqiDefine["JIEQI_URL"] + "/modules/article/articleinfo.php?id=" + article.articleid);
  static char strTemp[1024] = {0};
  copyChapterText(config, chapter, strTemp);
  XString::replaceAll(m_content, "{?$jieqi_content?}", strTemp);


  replaceTemplete(m_content, article);
  sprintf(strTemp, "%s/%d/%s", m_template.HtmlDir.c_str(), boost::lexical_cast<int>(article.articleid) / mover::SIZE_FILE_SPLIT_UNIT, article.articleid.c_str());
  m_file.checkDir(strTemp);
  strcat(strTemp, "/");
  strcat(strTemp, chapter.chapterid.c_str());
  strcat(strTemp, m_template.JieqiArticleConfigs["htmlfile"].c_str());
  return m_file.writeFile(m_content.c_str(), m_content.length(), strTemp);
}

void Builder::createIndex(articleInfo::ArticleInfo& article, const chapterInfo::ChapterInfo* chapters, const int len)
{
  static string strTemp;
  if(article.keywords.length() == 0)
  {
    article.keywords = article.articlename;
  }
  static int num2 = 1;
  static int num3 ;
  static string newValue = "";
  static string str6 = m_template.Templets_indextop + m_template.Templets_indexchapter + m_template.Templets_indexbottom ;
  static string str9 = "";
  static string str10 = "";
  static string str11 = "0";
  static string str13 = "";
  static string str14 = "";
  static string path;
  static string str15;
  for(int i = 0; i < len; i++)
  {
    num3 = boost::lexical_cast<int>(chapters[i].chaptertype);
    strTemp.assign(chapters[i].chaptername);
    replaceString(1, strTemp);
    if(num3 == 1)
    {
      if(num2 != 1)
      {
        newValue += str6;
      }
      newValue += m_template.Templets_indextop;
      if(chapters[i].chaptername.length() == 0)
      {
        str13.assign(m_template.Templets_indexvolume);
        XString::replaceAll(str13, "章节vname", m_template.Templets_indexchapterlist["vname"][0]);
        XString::replaceAll(str13, "{?$indexrows[i].vname?}", chapters[i].chaptername);
        XString::replaceAll(str13, "{?$indexrows[i].vid?}", chapters[i].chapterid);
        newValue += str13;
      }
      else
      {
        str14 = m_template.Templets_indexvolume;
        XString::replaceAll(str14, "章节vname", m_template.Templets_indexchapterlist["vname"][1]);
        XString::replaceAll(str14, "{?$indexrows[i].vname?}", chapters[i].chaptername);
        XString::replaceAll(str14, "{?$indexrows[i].vid?}", chapters[i].chapterid);
        newValue += str14;
      }
      newValue += m_template.Templets_indexbottom;
      num2 = 1;
    }//if(num3 == 1) end
    else
    {
      str10 = chapters[i].chaptername;
      str11 = chapters[i].chapterid;
      if(m_template.Templets_indexchapterlist.find("cname" + boost::lexical_cast<string>(num2)) == m_template.Templets_indexchapterlist.end())
      {
        num2 = 1;
        newValue = newValue + str6;
      }
      if (num2 == 1)
      {
        str6 = m_template.Templets_indextop + m_template.Templets_indexchapter + m_template.Templets_indexbottom;
      }
      if(chapters[i].chaptername.length() == 0)
      {
        strTemp = "章节cname";
        strTemp += boost::lexical_cast<string>(num2);
        XString::replaceAll(str6, strTemp , m_template.Templets_indexchapterlist["cname" + boost::lexical_cast<string>(num2)][0]);
        XString::replaceAll(str6, strTemp, m_template.Templets_indexchapterlist["cname" + boost::lexical_cast<string>(num2)][1]);
        XString::replaceAll(str6, "{?$indexrows[i].cname" + boost::lexical_cast<string>(num2) + "?}", chapters[i].chaptername);
        XString::replaceAll(str6, "{?$indexrows[i].curl" + boost::lexical_cast<string>(num2) +"?}", chapters[i].chapterid + m_template.JieqiArticleConfigs["htmlfile"]);
        XString::replaceAll(str6, "{?$indexrows[i].cid" + boost::lexical_cast<string>(num2) +"?}", chapters[i].chapterid);
      }
      else
      {
        strTemp = "章节cname";
        strTemp += boost::lexical_cast<string>(num2);
        XString::replaceAll(str6, strTemp, m_template.Templets_indexchapterlist["cname" + boost::lexical_cast<string>(num2)][1]);
        XString::replaceAll(str6, "{?$indexrows[i].cname" + boost::lexical_cast<string>(num2) + "?}", chapters[i].chaptername);
        XString::replaceAll(str6, "{?$indexrows[i].curl" + boost::lexical_cast<string>(num2) +"?}", chapters[i].chapterid + m_template.JieqiArticleConfigs["htmlfile"]);
        XString::replaceAll(str6, "{?$indexrows[i].cid" + boost::lexical_cast<string>(num2) +"?}", chapters[i].chapterid);
      }
      num2++;
      if(num2 > m_indexCols)
      {
        newValue = newValue + str6;
        num2 = 1;
      }
    }
  }
  if(num2 != 1)
  {
    newValue += str6;
  }
  for(int i = 1; i <= m_indexCols; i++)
  {
    XString::replaceAll(newValue, "章节cname" + boost::lexical_cast<string>(i), "&nbsp;");
  }
  string str18(m_template.Templets_indexhtml);
  XString::replaceAll(str18, "目录循环部分", newValue);
  replaceTemplete(str18, article);
  XString::replaceAll(str18, "{?$lastchapter?}", str10);
  XString::replaceAll(str18, "{?$url_lastchapter?}", str11 + m_template.JieqiArticleConfigs["htmlfile"]);
  string str19 = m_template.HtmlDir + "/" + boost::lexical_cast<string>(boost::lexical_cast<int>(article.articleid) / mover::SIZE_FILE_SPLIT_UNIT) ;
  str19 += "/" ;
  str19 += article.articleid;
  m_file.checkDir(str19.c_str());
  strTemp.assign(str19 + "/index" + m_template.JieqiArticleConfigs["htmlfile"]);
  m_file.writeFile(str18.c_str(), str18.length(), strTemp.c_str());
}
